<!--医院订单管理 -->
<template>
  <div class="order-management">
    <div class="title">
      <h1>医院订单管理</h1>
    </div>
    <tabs :is-hidden-zero="true" :tabs-arr="tabArr" @returnIndex="handletabs" />
    <el-form
      ref="queryForm"
      class="search_criteria"
      :inline="true"
      label-position="right"
      :label-width="'110px'"
      :model="queryCondition"
    >
      <el-form-item label="订单编号：">
        <el-input
          v-model.trim="queryCondition.orderCode"
          type="text"
          placeholder="请输入订单编号"
        />
      </el-form-item>
      <el-form-item label="供应商：">
        <el-select
          v-model="queryCondition.supplierName"
          filterable
          remote
          clearable
          placeholder="请输入关键字"
          :remote-method="getSupplier"
          :loading="loading"
        >
          <el-option
            v-for="item in supplierData"
            :key="item.orderCode"
            :label="item.supplierName"
            :value="item.supplierName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="医院：">
        <el-select
          v-model="queryCondition.hospitalName"
          filterable
          remote
          clearable
          placeholder="请输入关键字"
          :remote-method="getHospitalData"
          :loading="loading"
        >
          <el-option
            v-for="item in productLineData"
            :key="item.orderCode"
            :label="item.hospitalName"
            :value="item.hospitalName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型：">
        <el-select
          v-model="queryCondition.orderTypeId"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in typeList"
            :key="item.orderCode"
            :label="item.orderTypeName"
            :value="item.orderTypeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单提交日期：">
        <el-date-picker
          v-model="commitDate"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item class="form-button">
        <el-button type="primary" @click="queryFormQuery">查询</el-button>
        <el-button @click="queryFormReset">重置</el-button>
      </el-form-item>
    </el-form>
    <section class="el-container container-box is-vertical">
      <div class="exportex_box">
        <div class="operate">
          <el-button
            type="primary"
            :loading="detailExIsLoaded"
            size="mini"
            @click="exportDetailEx"
            >订单详情导出</el-button
          >
        </div>
        <div class="operate">
          <el-button
            type="primary"
            :loading="isLoaded"
            size="mini"
            @click="exportEx"
            >订单导出</el-button
          >
        </div>
      </div>
      <el-editable
        v-loading="tableLoading"
        height="400"
        :data="tableData"
        :columns="userManagement"
      >
        <template slot="default-action" slot-scope="scope">
          <el-button
            v-if="scope.row.orderStatus === 1"
            size="small"
            type="text text-primary"
            @click.stop="editButton(scope.row)"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.orderStatus === 1"
            size="small"
            type="text text-primary"
            @click.stop="deletebutton(scope.row)"
            >删除</el-button
          >
          <el-button
            v-if="[2, 6, 5, 7, 8].includes(scope.row.orderStatus)"
            size="small"
            type="text text-primary"
            @click="viewDetails(scope.row)"
            >查看</el-button
          >
          <el-button
            v-if="[5, 6].includes(scope.row.orderStatus)"
            size="small"
            type="text text-primary"
            @click="receivingClick(scope.row)"
            >收货</el-button
          >
        </template>
      </el-editable>
    </section>
    <el-pagination
      style="margin-top: 10px;"
      class="pagination"
      align="right"
      :current-page="curPage"
      :page-sizes="PAGE_NUMBER"
      :page-size="pageSize"
      :layout="PAGINATION_LAYOUT"
      :total="totalElements"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      title="取消通知"
      :visible.sync="dialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      width="28%"
      center
    >
      <p
        v-for="(item, i) in cancellationOrderList"
        :key="i"
        style="margin-left:8%;"
      >
        {{ item }}
      </p>
      <span v-if="cancelNotificationData.length > 5" style="margin-left:8%;"
        >...</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmCancellation"
          >知道了</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import tabs from '@components/tabs/index.vue';
import ElEditable from '@components/el-editable';
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common.js';
import { $loadFileSimply } from '@const/loadFileOps.js';
import { fileDownload } from '@const/utils.js';
import {
  getSupplierList,
  selectByHospitalName,
  orderStatus,
  afterSalesOrderManagement,
  statusQuantityQuery,
  deleteOrder,
  selectOrderNotice,
  updateFlag,
  downloadHospitalOrderList,
  downloadHospitalOrderDetailInfo
} from '@api/m_mall_web_v1.js';
import { tabArr, userManagement } from './const';

export default {
  components: { tabs, ElEditable },
  data() {
    return {
      orderTypeData: {
        '51': 'wholesale',
        '52': 'consign',
        '57': 'consume'
      },
      tableLoading: false,
      loading: false,
      dialogVisible: false,
      tabArr,
      userManagement,
      tableData: [], // 获取列表数据
      supplierData: [], // 获取产品线下拉搜索
      productLineData: [], // 获取医院下拉搜索
      typeList: [], // 获取订单类型
      commitDate: ['', ''], // 日期查询
      curPage: 1,
      PAGE_NUMBER, //  页码
      PAGINATION_LAYOUT, // 分页功能
      pageSize: PAGE_NUMBER[0], // 一页的数量
      totalElements: 0, // 总页数
      queryCondition: {
        orderStatus: null,
        system: 'H',
        orderCode: '', // 订单编号
        supplierName: '', // 供应商
        hospitalName: '', // 医院
        orderTypeId: '', // 订单类型
        busModelList: [51, 52, 57],
        commitDateEnd: '',
        commitDateStart: ''
      },
      exportQuery: {
        orderStatus: null,
        system: 'H',
        orderCode: '', // 订单编号
        supplierName: '', // 供应商
        hospitalName: '', // 医院
        orderTypeId: '', // 订单类型
        busModelList: [51, 52, 57],
        commitDateEnd: '',
        commitDateStart: ''
      },
      cancellationOrderList: [], // 获取取消订单内容
      cancellationOfOrder: [], // 获取取消订单的id
      cancelNotificationData: [],
      detailExIsLoaded: false,
      isLoaded: false
    };
  },
  created() {
    this.getOrdertype();
    this.getList();
    this.getNumberOfStates();
    this.getcancellationOfOrder();
  },
  mounted() {},
  methods: {
    // 切换各状态
    handletabs(index) {
      if (index === 0) {
        this.queryCondition.orderStatus = null;
      } else {
        this.tabArr.forEach((item, i) => {
          if (i === index) {
            this.queryCondition.orderStatus = item.val;
          }
        });
      }
      this.queryFormQuery();
    },
    getList() {
      this.tableLoading = true;
      const params = {
        ...this.queryCondition,
        page: this.curPage,
        pageSize: this.pageSize,
        commitDateStart: this.commitDate ? this.commitDate[0] : '',
        commitDateEnd: this.commitDate ? this.commitDate[1] : ''
      };
      this.$axios
        .$post(afterSalesOrderManagement, params)
        .then(res => {
          if (res.code === '0') {
            this.tableData = res.payload.content;
          }
          this.totalElements = res.payload.totalElements;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    // 获取订单各状态数量
    getNumberOfStates() {
      const params = {
        busModelList: [51, 52, 57]
      };
      this.$axios.$post(statusQuantityQuery, params).then(res => {
        if (res.code === '0') {
          if (res.payload === null) {
            this.tabArr.forEach(item => {
              const newItem = item;
              newItem.badge.value = 0;
            });
          }
          this.tabArr[1].badge.value = res.payload.submitCount; // 待提交
          this.tabArr[2].badge.value = res.payload.checkCount; // 待平台处理
          this.tabArr[3].badge.value = res.payload.harvestCount; // 待收货
          this.tabArr[4].badge.value = res.payload.partCount; // 部分收货
          //  this.tabArr[5].badge.value = res.payload.cancelCount	  		// 已取消
          //  this.tabArr[6].badge.value = res.payload.finishCount	  		// 已完成
        }
      });
    },
    // 删除
    deletebutton(row) {
      this.$confirm('是否要删除订单?', '删除订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.orderIds = row;
          this.$axios.$post(deleteOrder, [this.orderIds.orderId]).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
            this.getNumberOfStates();
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 获取供应商数据
    getSupplier(val) {
      if (val !== '') {
        this.loading = true;
        const params = {
          supplierName: val,
          busModelList: [51, 52, 57]
        };
        this.$axios
          .$post(getSupplierList, params)
          .then(res => {
            if (res.code === '0') {
              this.supplierData = res.payload;
            }
          })
          .catch(() => {})
          .finally(() => {
            this.loading = false;
          });
      }
    },
    // 获取医院下拉搜索数据
    getHospitalData(val) {
      if (val !== '') {
        this.loading = true;
        const params = {
          hospitalName: val,
          busModelList: [51, 52, 57]
        };
        this.$axios
          .$post(selectByHospitalName, params)
          .then(res => {
            if (res.code === '0') {
              this.productLineData = res.payload;
            }
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    // 获取订单类型
    getOrdertype() {
      const params = {
        busModel: 99,
        supplierCode: ''
      };
      this.$axios.$post(orderStatus, params).then(res => {
        this.typeList = res.payload || {};
      });
    },
    // 打开页面或者刷新页面展示取消订单的提示
    getcancellationOfOrder() {
      const params = {
        flag: 1,
        indexCode: 1
      };
      this.$axios.$post(selectOrderNotice, params).then(res => {
        const user = res.payload || {};
        this.cancelNotificationData = user;
        this.cancellationOrderList = user.map(item => item.remark).splice(0, 5);
        this.cancellationOfOrder = user
          .map(item => item.orderNoticeId)
          .splice(0, 5);
        if (this.cancellationOrderList.length > 0) {
          this.dialogVisible = true;
        }
      });
    },
    // 取消订单确认
    confirmCancellation() {
      this.dialogVisible = false;
      const ids = this.cancellationOfOrder;
      this.$axios.$post(updateFlag, ids);
    },
    // 查询
    queryFormQuery() {
      this.curPage = 1;
      this.exportQuery = { ...this.queryCondition };
      this.exportQuery.commitDateStart = this.commitDate
        ? this.commitDate[0]
        : '';
      this.exportQuery.commitDateEnd = this.commitDate
        ? this.commitDate[1]
        : '';
      this.getList();
    },
    // 重置
    queryFormReset() {
      // eslint-disable-next-line no-unused-expressions
      (this.queryCondition = {
        orderStatus: this.queryCondition.orderStatus,
        orderCode: '', // 订单编号
        orderTypeId: '', // 订单类型
        returnReasonCode: '', // 退换货原因
        hospitalName: '', // 医院
        supplierName: '', // 供应商
        busModelList: [51, 52, 57],
        commitDateEnd: '',
        commitDateStart: ''
      })((this.exportQuery = { ...this.queryCondition }));
      this.commitDate = ['', ''];
      this.curPage = 1;
      this.getList();
    },
    // 页码更改
    handleSizeChange(size) {
      this.curPage = 1;
      this.pageSize = size;
      this.getList();
    },
    //  切换不一样的页面，重置一切数据
    handleCurrentChange(curPage) {
      this.curPage = 1;
      this.curPage = curPage;
      this.getList();
    },
    //  点编辑跳转创建采购页面
    editButton(row) {
      this.$router.push({
        path: `/hospital-purchase-order/${
          this.orderTypeData[row.busModel]
        }/add`,
        query: {
          orderId: row.orderId
        }
      });
    },
    //  跳转详情页
    viewDetails(row) {
      const url =
        row.busModel === '57'
          ? '/hospital-purchase-order/list/consume-details'
          : '/hospital-purchase-order/list/details';
      this.$router.push({
        query: {
          orderId: row.orderId,
          orderCode: row.orderCode
        },
        path: url
      });
    },
    // 跳转详情页
    receivingClick(row) {
      this.$router.push({
        query: {
          orderId: row.orderId,
          orderCode: row.orderCode
        },
        path: `/hospital-purchase-order/list/receive`
      });
    },
    // 详情导出
    exportDetailEx() {
      if (this.tableData && this.tableData.length > 0) {
        this.detailExIsLoaded = true;
        const query = {
          busModelList: [51, 52, 57],
          ...this.exportQuery
        };
        $loadFileSimply({
          method: 'post',
          url: downloadHospitalOrderDetailInfo,
          timeout: '0',
          data: {
            ...query
          }
        })
          .then(res => {
            if (res.byteLength) {
              fileDownload(res, `产品详情${this.getCurrentDateTime()}.xlsx`);
              this.detailExIsLoaded = false;
            } else {
              this.detailExIsLoaded = false;
              this.$message({
                message: '导出失败',
                type: 'warning'
              });
            }
          })
          .catch(() => {
            this.detailExIsLoaded = false;
            this.$message({
              message: '导出失败',
              type: 'warning'
            });
          });
      } else {
        this.$message({
          message: '暂无可导出数据',
          type: 'warning'
        });
      }
    },
    //  导出
    exportEx() {
      if (this.tableData && this.tableData.length > 0) {
        this.isLoaded = true;
        const query = {
          busModelList: [51, 52, 57],
          ...this.exportQuery
        };
        $loadFileSimply({
          method: 'post',
          url: downloadHospitalOrderList,
          timeout: '0',
          data: {
            ...query
          }
        })
          .then(res => {
            if (res.byteLength) {
              fileDownload(res, `订单${this.getCurrentDateTime()}.xlsx`);
              this.isLoaded = false;
            } else {
              this.isLoaded = false;
              this.$message({
                message: '导出失败',
                type: 'warning'
              });
            }
          })
          .catch(() => {
            this.isLoaded = false;
            this.$message({
              message: '导出失败',
              type: 'warning'
            });
          });
      } else {
        this.$message({
          message: '暂无可导出数据',
          type: 'warning'
        });
      }
    },
    formatZero(n) {
      if (n >= 0 && n <= 9) {
        return `0${n}`;
      }
      return n;
    },
    // 获取当前日期和时间
    getCurrentDateTime() {
      const t = new Date();
      const year = t.getFullYear();
      const month = t.getMonth() + 1;
      const day = t.getDate();
      return `${year}-${this.formatZero(month)}-${this.formatZero(day)}`;
    }
  }
};
</script>
<style lang="less" src="./index.less"></style>
